package com.link.base.base.address.controller;

import com.link.base.basic.service.BasicCommonService;
import com.link.base.base.address.model.AddrTree;
import com.link.base.base.address.model.AllAddress;
import com.link.base.base.address.service.AllAddressService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.UserUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @version 1.0
 * @date: 2018/11/8 10:18
 */

@Controller
@RequestMapping("/link/alladdress")
public class AllAddressController extends BasicController<AllAddress> {

    @Resource
    private AllAddressService allAddressService;

    @Resource
    private BasicCommonService basicCommonService;

    @Resource
    private KeyGenerateService keyGenerateService;

    @Override
    public BasicService<AllAddress> getBasicService() throws Exception {
        return allAddressService;
    }

    ;

    /**
     * 父名称列表的跳转
     *
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/parentPicklist")
    public String parentPicklist(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("type", qps.getAttr2());
        return "picklist/ParentOfAcctPickList";
    }

    @RequestMapping(value = "/parentList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> parentList(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        LCLogger.info().withMessageKey("parentList").withMessage(">>>>recive arrr_type is>>>>>" + qps.getAttr2() + "<<<<<<").flush();
        AllAddress entity = (AllAddress) BasicModel.transformClass(AllAddress.class, qps);
        try {
            entity.setAttr4(qps.getAttr2());
            //设置安全性
            entity.preDealSecurity(request);
            List<AllAddress> list = allAddressService.queryByTypeAddressListPage(entity);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(entity, list.size()));

        } catch (BasicServiceException e1) {
            LCLogger.withException(e1);
            result.put("success", false);
            result.put("result", e1.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新当前地址的父id
     *
     * @param record
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/parentUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> chargerUpdate(@JsonParam AllAddress record, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            allAddressService.parentIdUpdate(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>查询树形结构省市县</p>
     *
     * @param session
     * @param request
     * @param response
     * @return
     * @author 王艳
     */
    @RequestMapping(value = "/queryAllAddress", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAllAddress(@JsonParam QueryParams qps, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        AddrTree entity = new AddrTree();
        try {
            List<AddrTree> list = allAddressService.queryAllAddress(entity);

            for (AddrTree state : list) {
                if (state.getChildren().size() == 1) {
                    AddrTree city = state.getChildren().get(0);
                    if (StringUtils.isBlank(city.getName())) {
                        state.setChildren(null);
                    }
                }
                if (null != state.getChildren()) {
                    for (AddrTree city : state.getChildren()) {
                        if (city.getChildren().size() == 1) {
                            AddrTree county = city.getChildren().get(0);
                            if (StringUtils.isBlank(county.getName())) {
                                city.setChildren(null);
                            }
                        }
                    }
                }
            }
            result.put("success", true);
            result.put("rows", list);
            result.put("total", list.size());

        } catch (BasicServiceException e1) {
            LCLogger.withException(e1);
            result.put("success", false);
            result.put("result", e1.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/updateById", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> updateById(@RequestBody AllAddress model, HttpServletRequest request,
                                          HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            String privateAddrflag = UserUtil.getUser().getUserPrivateAddr();
            String addrFlag = "Y";
            if (!addrFlag.equals(privateAddrflag)) {
                throw new ServiceException("ADDRESS-002");
            }
            if (model.getId() != null) {
                //更新
                allAddressService.update(model);
                AllAddress resultAddrQuery = new AllAddress();
                resultAddrQuery.setId(model.getId());
                AllAddress resultAddr = allAddressService.queryById(resultAddrQuery);
                result.put("result", resultAddr);
                result.put("success", true);
            } else {
                Long id = keyGenerateService.keyGenerate();
                model.setId(id);
                allAddressService.insert(model);
                AllAddress resultAddrQuery = new AllAddress();
                resultAddrQuery.setId(model.getId());
                AllAddress resultAddr = allAddressService.queryById(resultAddrQuery);
                result.put("result", resultAddr);
                result.put("success", true);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

}
